<template>
  <h1>Welcome to my app</h1>
  <div>
    <pre>{{ history }}</pre>
  </div>
  <div>
    <el-input v-model="inputText" placeholder="Enter text" @keyup.enter="handleInput"/>
  </div>
</template>

<script setup>
import {ref} from "vue";

const inputText = ref("");
const history = ref('');

const handleInput = () => {
  // 保留输入值到一个临时变量中
  const userInput = inputText.value;

  // 更新历史记录，添加用户提问
  if (userInput.trim()) {  // 确保输入不为空或只包含空格
    history.value += `\n` + `User: ${userInput}\n ` + `\nSystem: `;  // 追加用户提问

    // 清空输入框
    inputText.value = "";

    // 创建 EventSource 实例
    const eventSource = new EventSource(`http://localhost:8000/app/sse/?ask=` + encodeURIComponent(userInput));

    // 处理消息，添加系统回答
    eventSource.onmessage = (event) => {
      history.value += `${event.data}`;  // 追加系统回答并换行
    };

    // 处理错误
    eventSource.onerror = (event) => {
      console.log('EventSource failed:', event);
      eventSource.close();  // 关闭连接
    };
  }
};
</script>
